import {
  isSuccessReqBackend,
  getBackendDataItems,
  getBackendData,
  fakerReqBackend,
} from "@gd-accbuild-core/config/utils"; //, dynmicImport
import getMetaListFromColumns from "./getMetaListFromColumns";
/**
 * 请求获取vmCode 的 columns 和 对应的data
 * @param {Array} allVmTemplatesConfig 需要请求的vmTemplateConfig;[{templateIdx,reqDataType,vmCode:"···",params:{},isEnterReqData:false}]
 * @param {String} curResourceRealPageKey 用于动态import页面级别自定义元数据
 */
export default async ({
  allVmTemplatesConfig,
  curResourceRealPageKey,
  store,
  globalHttpApis,
  templateIdx,
  appendReqParams,
  overrideParams,
  isUseStaticResource,
  staticResource,
}) => {
  const { getMetaListByVmCode, get, getList } = globalHttpApis;
  let allVmCodesColumns = [];
  let allVmCodesData = [];
  const promiseColsArr = [];
  const promiseDataListArr = [];
  const filteredVmTemplatesConfig =
    typeof templateIdx === "number"
      ? [allVmTemplatesConfig[templateIdx]]
      : allVmTemplatesConfig;
  filteredVmTemplatesConfig.forEach((vmTemplateConfig, idx) => {
    let appendGetDataParams = {};
    if (typeof templateIdx === "number" && templateIdx === idx) {
      appendGetDataParams = { ...appendReqParams };
    }
    console.log(overrideParams, "-----------------------");
    //TODO:FIXME: 具有 vmTemplateConfig._gdAccbuild_GdSysProject_proxyFlag 标记的 说明是设计器发起,请求都必须发到优速搭服务器上,再转发到目标域名;为了安全控制
    promiseColsArr.push(
      getMetaListByVmCode(
        {
          moduleCode: vmTemplateConfig.moduleCode,
          vmCode: vmTemplateConfig.vmCode,
        },
        vmTemplateConfig
      )
    );
    const isEnterReqData = vmTemplateConfig?.isEnterReqData ?? true;
    const reqDataType = vmTemplateConfig?.reqDataType ?? "Items";
    const getDataByVmCode = reqDataType === "Items" ? getList : get;
    if (isEnterReqData) {
      promiseDataListArr.push(
        getDataByVmCode({
          moduleCode: vmTemplateConfig.moduleCode,
          vmCode: vmTemplateConfig.vmCode,
          params: {
            ...vmTemplateConfig.params,
            parentId: null,
            ...appendGetDataParams,
          },
          vmTemplateConfig: vmTemplateConfig,
        })
      );
    } else {
      promiseDataListArr.push(fakerReqBackend());
    }
  });
  /**
   * 获取res.data.items的返回值
   */
  const getResItems = (allRes) => {
    const curRetVal = [];
    if (allRes.length > 0) {
      allRes
        .map((res) => getBackendDataItems(res))
        .forEach((data, idx) => {
          curRetVal.push({
            templateIdx: filteredVmTemplatesConfig[idx].templateIdx,
            vmCode: filteredVmTemplatesConfig[idx].vmCode,
            data,
          });
        });
    }
    return curRetVal;
  };
  /**
   * 获取res.data的返回值
   *  */
  const getResData = (allRes) => {
    const curRetVal = [];
    allRes
      .map((res, index) => {
        return (filteredVmTemplatesConfig[index]?.reqDataType ?? "Items") ===
          "Items"
          ? getBackendDataItems(res)
          : getBackendData(res);
      })
      .forEach((data, idx) => {
        curRetVal.push({
          templateIdx: filteredVmTemplatesConfig[idx].templateIdx,
          vmCode: filteredVmTemplatesConfig[idx].vmCode,
          isEnterReqData:
            filteredVmTemplatesConfig[idx]?.isEnterReqData ?? true,
          reqDataType: filteredVmTemplatesConfig[idx]?.reqDataType ?? "Items",
          data,
        });
      });
    return curRetVal;
  };
  try {
    const colsRes = await Promise.all(promiseColsArr);
    const dataListRes = await Promise.all(promiseDataListArr);

    if (colsRes.every((res) => isSuccessReqBackend(res))) {
      allVmCodesColumns = getResItems(colsRes);
    }
    if (dataListRes.every((res) => isSuccessReqBackend(res))) {
      allVmCodesData = getResData(dataListRes);
    }
  } catch (err) {
    console.log(err, "报错");
  }
  let curPageDynmicComponentsConfigs = {};
  try {
    /* await dynmicImport(curResourceRealPageKey + '/index.js').then(res => {
            curPageDynmicComponentsConfigs = res?.dynmicComponentsConfigs ?? {}
        }).catch(err => {
            //console.log("动态导入失败,文件路径存在但执行报错", err);
        }) */
  } catch (error) {
    //console.log("动态导入失败,导入文件路径不存在", error)
  }
  //TODO:FIXME: 从本地获取所有vmCode的多标签枚举数据
  const allTabObjHolderConfigs = {
    curResourceRealPageKey: {
      templateIdx: {
        //······
      },
    },
  };
  const promiseArrGetMetaListFromColumns = [];
  allVmCodesColumns.forEach((el, index) => {
    const tabObjHolderConfig = allTabObjHolderConfigs?.[
      curResourceRealPageKey
    ]?.[el.templateIdx] ?? {
      1: {
        key: "Tab:BaseInfo",
        name: "标签1",
      },
      2: {
        key: "Tab:StoreInfo",
        name: "标签2",
      },
      3: {
        key: "Tab:ProductInfo",
        name: "标签3",
      },
      4: {
        key: "Tab:QualityInfo",
        name: "标签4",
      },
      5: {
        key: "Tab:PurchaseInfo",
        name: "标签5",
      },
      6: {
        key: "Tab:LabelInfo",
        name: "标签6",
      },
    }; //{columns, customizeMetaConfig={}, tabObjHolderConfig={}, store=null}
    promiseArrGetMetaListFromColumns.push(
      getMetaListFromColumns({
        columns: el.data,
        customizeMetaConfig: curPageDynmicComponentsConfigs,
        tabObjHolderConfig,
        store,
        isUseStaticResource,
        staticResource,
      })
    ); //, d:allVmCodesData[index]
  });

  const allVmCodesMetaList = await Promise.all(
    promiseArrGetMetaListFromColumns
  );
  //TODO:FIXME: allVmCodesColumns这个需要调用getMetaListFromColumns 转化成 搜索、弹窗、表格 的 metaList
  return {
    //allVmCodesColumns,
    allVmCodesMetaList,
    allVmCodesData,
  };
};
